package com.example.toutiao.ui.activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.toutiao.R;
import com.example.toutiao.adapter.CartAdapter;
import com.example.toutiao.db.CartItem;
import com.example.toutiao.db.DatabaseHelper;

import java.util.List;

// 购物车列表
public class CartActivity extends AppCompatActivity {

    private RecyclerView recyclerViewCart;
    private CartAdapter cartAdapter;
    private Button btn_clear_cart;
    private DatabaseHelper dbHelper;

    @Override
    @SuppressLint("MissingInflatedId")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart);
        TextView tabBarTitle = findViewById(R.id.tabBarTitle);
        tabBarTitle.setText("购物车列表");
        // 从 SharedPreferences 获取当前登录的用户名
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", MODE_PRIVATE);
        String currentUsername = sharedPreferences.getString("username", null);

        // 获取购物车的 RecyclerView
        recyclerViewCart = findViewById(R.id.recyclerViewCart);
        btn_clear_cart = findViewById(R.id.btn_clear_cart);
        dbHelper = new DatabaseHelper(this);


        // 检查用户名是否为空
        if (currentUsername == null) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取该用户的购物车商品
        List<CartItem> cartItems = dbHelper.getCartItemsByUsername(currentUsername);

        Log.d("用户商品：", cartItems.toString());

        if (cartItems.isEmpty()) {
            Toast.makeText(this, "购物车为空", Toast.LENGTH_SHORT).show();
        } else {
            // 创建适配器并设置给 RecyclerView
            cartAdapter = new CartAdapter(this, cartItems, dbHelper);
            recyclerViewCart.setAdapter(cartAdapter);
            recyclerViewCart.setLayoutManager(new LinearLayoutManager(this));
        }


        btn_clear_cart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dbHelper.deleteCartItemsByUsername(currentUsername);
                cartAdapter.setData(dbHelper.getCartItemsByUsername(currentUsername));
            }
        });
    }
}
